<template>
  <div class="private-chat-container">
    <!-- 左侧私聊用户列表 -->
    <div class="user-list">
      <div 
        v-for="(user, index) in privateChatUsers" 
        :key="index"
        class="user-item"
        :class="{ active: activeUserIndex === index }"
        @click="startPrivateChat(user.username, index)"
      >
        <div class="avatar">{{ user?.username?.charAt(0).toUpperCase() }}</div>
        <span class="username">{{ user?.username }}</span>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div class="message-area">
        <div v-for="(msg, index) in messages" :key="index" class="message-bubble">
          <div class="message-meta">
            <span class="sender">{{ msg.senderUsername }}</span>
            <span class="time">{{ msg.createAt.replace('T', ' ') }}</span>
          </div>
          <div class="message-content">{{ msg.content }}</div>
        </div>
      </div>
      <div class="input-area">
        <el-input v-model="message" @keydown.enter.native="sendMessage"></el-input>
        <el-button @click="sendMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      privateChatUsers: [], 
      message: '',
      ws: null,
      messages: [],
      currentChatUser: null,
      activeUserIndex: -1, // 新增当前选中用户索引
      chatUsername: '', // 新增接收者用户名
      loadType: {
        old: 0, // 加载旧消息
        new: 1 // 加载新消息
      },
      messageListReady: false, // 消息列表是否加载完成的标志
      offset: 0, // 消息列表偏移量
    }
  },
  created() {
    this.loadPrivateChatUsersList()
    this.initActiveUserIndex()
    this.loadChatMessage()
    this.initWebSocket()
  },
  mounted() {
    const messageArea = this.$el.querySelector('.message-area');
    if (messageArea) {
      messageArea.addEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    initWebSocket() {
      const token = JSON.parse(localStorage.getItem('user')).token
      // 修改WebSocket连接地址，添加目标用户参数
      this.ws = new WebSocket(
        `ws://localhost:8080/ws/chat?token=${token}&to=${this.$router.currentRoute.params.username}`
      )
      // 在initWebSocket方法中补全消息接收处理
      this.ws.onmessage = (event) => {
        console.log('Received message:', event.data)
        const data = JSON.parse(event.data)
        console.log("接收到消息前的高度：" + this.$el.querySelector('.message-area').scrollHeight)
        this.messages.push({
          senderUsername: data.senderUsername,
          content: data.content,
          createAt: new Date(data.createAt).toISOString().split('.')[0]
        })
        this.$nextTick(() => {
          const oldScrollHeight = this.$el.querySelector('.message-area').scrollHeight;
          this.scrollTo(this.loadType.old, oldScrollHeight)
        })
        
      }
      this.ws.onopen = () => {
        console.log('WebSocket connected')
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error)
      }

      this.ws.onclose = () => {
        console.log('WebSocket disconnected')
      }

      this.ws.beforeclose = () => {
        console.log('WebSocket beforeclose')
        const key = JSON.parse(localStorage.getItem('user')).username + "-" + this.currentChatUser;
        console.log(key);
        this.messages.push({
          key: key
        })
      }
    },
    sendMessage() {
      if (this.message.trim() && this.ws.readyState === WebSocket.OPEN) {
        const msgObj = {
          content: this.message,
          receiverUsername: this.receiveUsername, // 添加接收者字段
          createAt: new Date().getTime(),
          type: 1
        }
        console.log(msgObj);
        this.ws.send(JSON.stringify(msgObj))
        this.message = ''
      }
    },
    // 加载私聊用户列表
    async loadPrivateChatUsersList() {
      try {
        this.privateChatUsers = JSON.parse(localStorage.getItem('chatList') || '[]');
        this.currentChatUser = this.privateChatUsers[0]?.username; // 初始化当前聊天用户
        if (this.privateChatUsers.length === 0) {
          this.$message.info('暂无私聊联系人');
        }
      } catch (error) {
        console.error('获取私聊用户列表失败:', error);
        this.$message.error('获取联系人失败');
      }
    },
    // 开始私聊
    startPrivateChat(username, index) {
      console.log(username);
      this.currentChatUser = username;
      this.activeUserIndex = index; // 设置当前选中索引
      this.messages = [];
      this.messageListReady = false; // 重置消息列表加载标志
      this.offset = 0; // 重置偏移量
      this.initWebSocket();
      this.$axios.post('message/getChatMessageByMutualUsername',{
        currentUsername: JSON.parse(localStorage.getItem('user')).username,
        chatUsername: username,
        offset: this.offset
      }).then(res => {
        console.log(res.data);
        this.messages.push(...res.data.data);
        this.$nextTick(() => {
          // 私聊界面初始消息，滚动到底部
          console.log("开始私聊界面初始消息，滚动到底部");
          const oldScrollHeight = this.$el.querySelector('.message-area').scrollHeight;
          this.scrollTo(this.loadType.new, oldScrollHeight);
          this.$nextTick(() => {
            this.messageListReady = true;
          })
        })
      })
      
      
    },
    // 初始化当前选中用户索引
    initActiveUserIndex() {
      const currentChatUsername = this.$router.currentRoute.params.username; // 获取当前路由参数中的用户名
      if (!currentChatUsername) {
        console.log("没有获取到chatusername");
        this.activeUserIndex = 0; // 如果没有用户名，将索引设置为-1
        this.currentChatUser = this.privateChatUsers[0]?.username;
      }else{
        console.log("获取到chatusername");
        this.activeUserIndex = this.privateChatUsers.findIndex(user => user.username === currentChatUsername); // 查找当前用户在列表中的索引 
        if (this.activeUserIndex === -1) {
          this.privateChatUsers.push({ username: currentChatUsername }); // 如果用户不在列表中，将其添加到列表中
          this.activeUserIndex = this.privateChatUsers.length - 1; // 设置当前选中索引为新添加的用户
        }
        this.currentChatUser = currentChatUsername;
      }
      
    },
    // 加载聊天消息
    loadChatMessage(){
      try {
        this.messages = []; // 清空消息列表
        this.offset = 0; // 重置偏移量
       this.$axios.post('message/getChatMessageByMutualUsername',{
        currentUsername: JSON.parse(localStorage.getItem('user')).username,
        chatUsername: this.currentChatUser,
        offset: this.offset
       }).then(res => {
        this.messages.push(...res.data.data);
        this.messages.reverse();
        this.$nextTick(() => {
          const oldScrollHeight = this.$el.querySelector('.message-area').scrollHeight;
          // 初始化消息界面，滚动到底部
          this.scrollTo(this.loadType.new, oldScrollHeight);
          this.messageListReady = true;
        })
       })
      } catch (error) {
        console.error('获取消息列表失败:', error);
        this.$message.error('获取消息列表失败');
      }
    },
    // 加载更多消息
    loadMoreMessages() {
      this.$axios.post('message/getChatMessageByMutualUsername',{
        currentUsername: JSON.parse(localStorage.getItem('user')).username,
        chatUsername: this.currentChatUser,
        offset: this.offset 
      }).then(res => {
        const messageList = res.data.data.reverse();
        const oldScrollHeight = this.$el.querySelector('.message-area').scrollHeight;
        this.messages = messageList.concat(this.messages);
        this.offset = this.messages.length;
        this.$nextTick(() => {
          this.scrollTo(this.loadType.old, oldScrollHeight);
        });
      })
    },
    //监听滚动事件，判断是否滚动到顶部
    handleScroll() {
      const container = this.$el.querySelector('.message-area');
      if (container.scrollTop === 0 && this.messageListReady) {
        console.log('滚动到顶部，加载更多消息');
        // 滚动到顶部，加载更多消息
        this.offset = this.messages.length ;
        this.loadMoreMessages();
      } 
    },
    // 滚动到指定位置
    scrollTo(loadType, oldScrollHeight) {
      const container = this.$el.querySelector('.message-area');
      this.$nextTick(() => {
        if (loadType === this.loadType.old) {
        console.log("滚动到记录位置");
        container.scrollTop = container.scrollHeight - oldScrollHeight;
      } else if (loadType === this.loadType.new) {
        console.log("滚动到底部");
        this.$nextTick(() => {
          container.scrollTop = container.scrollHeight;
        });
      }
      });
      
    }
  },
  watch: {
  }
}
</script>

<style scoped>
@import url('../assets/css/views/chat-private.css');
</style>
